<template>
  <div class="container">
    <el-row class="mb10">
      <el-col :span="16">
        <div class="flex">
          <el-select
            v-model="data.searchParams.projectYear"
            placeholder="年份"
            style="width: 10%"
            @change-value="changeValue"
            clearable
          >
            <el-option
              :label="item.itemText"
              :value="item.itemValue"
              :key="item.itemValue"
              v-for="item in options.yearList"
            />
          </el-select>
          <SelectOption
            :options="options.unitnameList"
            :placeholder="'奖项种类'"
            @change-value="changeValue1"
          >
          </SelectOption>
          <div class="conUnitName">
            <el-cascader
              popper-class="gy-cascader"
              :options="data.orgAllList"
              :props="data.popupTreeProps"
              v-model="data.searchParams.applyUnitName"
              :show-all-levels="false"
              placeholder="申报单位"
              clearable
            >
              <template #default="{ data }">
                <el-tooltip
                  :disabled="data.name.length < 13"
                  class="item"
                  effect="dark"
                  :content="data.name"
                  placement="bottom-start"
                >
                  <span>{{ data.name }}</span>
                </el-tooltip>
              </template>
            </el-cascader>
          </div>

          <el-button class="ordinary" @click="search()">搜索</el-button>
        </div>
      </el-col>
      <el-col :span="8" align="right">
        <!-- <el-button class="ordinary" @click="getExport()" v-limit="'KJSL:PTJCJS:KJZYZHPT:EXPERT'"
          >批量导出</el-button
        > -->
      </el-col>
    </el-row>
    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
      <el-tab-pane label="人员发放清单" name="first"></el-tab-pane>
      <el-tab-pane label="奖金分配明细表" name="second"></el-tab-pane>
      <el-tab-pane label="科技奖励发放金额统计表" name="third"></el-tab-pane>
      <el-tab-pane label="奖励分配一览表" name="fourth"></el-tab-pane>
    </el-tabs>
    <div>
      <Table
        :loading="data.isLoading"
        :tableArr="data.allTableData"
        :operate="true"
        :pagination="data.page"
        :columns="data.columns"
        :total="data.page.total"
        @delectTable="delectIds"
        @currentChange="currentChange"
        @sizeChange="sizeChange"
        :span-method="spanMethod"
        :border="true"
      >
      </Table>
    </div>
  </div>
</template>
<script lang="js">
import * as proxy from "@/constants/proxy"
import request from "@/utils/request"
import Api from '@/views/science/api/awards'
import SelectOption from '@/views/science/components/selectOption'
import Table from '@/views/science/components/table/table.vue'
import { Modals, tips } from '@/views/science/components/tips/tips'
import {computed, onMounted, reactive, ref} from 'vue'
import { useStore } from 'vuex'
import tableData from './tableHeader.json'



export default {
  components: {
    SelectOption,
    Table,
  },
  setup() {
    const store = useStore()
    const activeName = ref('first')//tab切换
    let data = reactive({
      orgAllList: [],
      popupTreeProps: {
        label: 'name',
        children: 'children',
        value:'id',
        checkStrictly: true,
      },
      isLoading: false,
      page: { page: 1, limit: 10, total: 0 },
      currentIndex:0,
      ids: [],
      searchParams: {
        projectYear: '', // 年份
        awardApplyName: '', // 申报奖项
        applyUnitName: '',
        "page": 1,
        "pageSize": 10,
        "remark1":0
      },
      allTableData: [],
      columns: tableData.personTableHeader,
    })
    // ...
    // 合并单元格,通过过滤 allTableData 数组，找出所有 applyUser 值与当前行 applyUser 值相同的行，然后计算这些行的数量 rowspan。
    const spanMethod = ({ row, column, rowIndex, columnIndex }) => {
      if(Number(data.currentIndex)===0){
        // 如果是人员发放清单，需要合并，第三列，根据applyUser合并
        if (columnIndex === 2 || columnIndex ===data.columns.length+1) {
          const sameApplyUserRows = data.allTableData.filter(item => item.applyUser === row.applyUser);
          if (sameApplyUserRows.length > 0 && sameApplyUserRows[0] === row) {
            return [sameApplyUserRows.length, 1];
          } else {
            return [0, 0];
          }
        }
      }else if(Number(data.currentIndex)===1){
        // 如果是奖金分配明细表，需要合并，第一列，根据orgName合并
        if (columnIndex===data.columns.length+1) {
          const sameApplyUserRows = data.allTableData.filter(item => item.orgName === row.orgName);
          if (sameApplyUserRows.length > 0 && sameApplyUserRows[0] === row) {
            return [sameApplyUserRows.length, 1];
          } else {
            return [0, 0];
          }
        }
      }
      return [1, 1];
    }

    const handleClick = (tab) => {
      console.log(tab.index,'handleClick')
      data.currentIndex = tab.index
      data.searchParams.remark1 = tab.index
      getListData()
      if(tab.index==0){
        data.columns = tableData.personTableHeader
      }else if(tab.index==1){
        data.columns = tableData.detailTableHeader
      }else if(tab.index==2){
        data.columns = tableData.statisticsTableHeader
      }else if(tab.index==3){
        data.columns = tableData.listTableHeader
      }
    }
    const loading = ref(true)//加载
    // 存储下拉框数组的对象
    const options = reactive({
      projectnameList: computed(() => store.state.technologyStrength.KJSL_DECLARATION_TYPE),
      unitnameList: computed(() => store.state.technologyStrength.KJSL_APPLYING_FOR_AWARDS1),
      yearList: [
        { itemText: '全部年份', itemValue: '' },
        { itemText: '2026年', itemValue: '2026' },
        { itemText: '2025年', itemValue: '2025' },
        { itemText: '2024年', itemValue: '2024' },
        { itemText: '2023年', itemValue: '2023' },
        { itemText: '2022年', itemValue: '2022' },
        { itemText: '2021年', itemValue: '2021' },
        { itemText: '2020年', itemValue: '2020' },
        { itemText: '2019年', itemValue: '2019' },
        { itemText: '2018年', itemValue: '2018' },
      ],//年份
    })
    const changeValue = (item) => data.searchParams.projectYear = item.itemValue
    const changeValue1 = (item) => data.searchParams.awardApplyName = item.itemValue

    data.searchParams.page = data.page.page
    data.searchParams.pageSize = data.page.limit

    const getListData = () => { // 获取列表数据
      loading.value = true   // 加载
      data.isLoading = true
      let obj = {...data.searchParams}

      obj.applyUnitName = obj.applyUnitName ? obj.applyUnitName[obj.applyUnitName.length - 1] : ''
      console.log('obj',obj);
      Api.getbonusShareList(obj)
        .then((res) => { // 获取列表数据
          let resData = res.data.data // 获取列表数据
          // 创建一个Map对象来存储每个人的amount总和
          if(Number(data.currentIndex)===0){
            const bonusSumMap = new Map();
            resData.records.forEach(record => {
              if (bonusSumMap.has(record.applyUser)) {
                bonusSumMap.set(record.applyUser, bonusSumMap.get(record.applyUser) + record.amount);
              } else {
                bonusSumMap.set(record.applyUser, record.amount);
              }
            });
            // 将amount总和赋值到bonussum字段上
            resData.records.forEach(record => {
              record.bonussum = bonusSumMap.get(record.applyUser);
            });
            // 对数据进行排序，按照applyUser字段排序
            resData.records.sort((a, b) => a.applyUser.localeCompare(b.applyUser));
          }else if(Number(data.currentIndex)===1){
            const bonusSumMap = new Map();
            resData.records.forEach(record => {
              if (bonusSumMap.has(record.orgName)) {
                bonusSumMap.set(record.orgName, bonusSumMap.get(record.orgName) + record.amount);
              } else {
                bonusSumMap.set(record.orgName, record.amount);
              }
            });
            // 将amount总和赋值到bonussum字段上
            resData.records.forEach(record => {
              record.bonussum = bonusSumMap.get(record.orgName);
            });
            // 对数据进行排序，按照applyUser字段排序
            resData.records.sort((a, b) => a.orgName.localeCompare(b.orgName));
          }
          data.allTableData = resData.records   // 获取列表数据
          data.page.total = resData.total   // 获取列表数据
          data.isLoading = false
        })
        .finally(() => { // 获取列表数据
          loading.value = false  // 获取列表数据
        }).catch((error) => {
          data.isLoading = false
        })
    }
    // 点击查询按键，分页设置为当前页为1，
    const search = () => {
      console.log('搜索',data.searchParams);
      data.page.page = 1
      getListData()
    }
    const delectIds = (ids) => {
      data.ids = ids
      console.log(data.ids,'data.ids');
    }
    const currentChange = (current) => {
      data.searchParams.page = current
      getListData()
    }
    const sizeChange = (size) => {
      data.params.pageSize = size
      getListData()
    }
    const getExport = () => {
      let msg = '是否导出全部数据'
      if (data.ids.length > 0) {
        msg = '是否导出所选数据'
      }
      Modals(msg, '提示', 'warning').then(async () => {
        const params = {
          ...data.searchParams,
          ids: data.ids
        }
        await Api.exportBonus(params, "科技成果奖励")
      }).catch(() => {
        console.log("点击了取消")
      })
    }

    const getOrgList = () =>{
      return request({
        url: proxy.CHECC_API_CMS + "/org/getSysOrgList",
        method: "get",
      }).then(res =>{
        data.orgAllList = res.data.data
      })
    }
    getListData()
    // 发送请求
    onMounted(() => {
      // 获取单位信息
      getOrgList();
    });

    return {
      delectIds,
      changeValue,
      changeValue1,
      currentChange,
      sizeChange,
      search,
      activeName,
      options,
      data,
      getListData,
      handleClick,
      getExport,
      spanMethod,
    }
  },
}
</script>
<style lang="scss" scoped>
.container {
  background-color: white;
  padding: 20px;
}
.conUnitName {
  display: inline-block;
  margin-bottom: -10px;
  margin-right: 15px;
  padding-bottom: 10px;
  margin-top: -5px;
}
/deep/.el-dialog > .el-dialog__footer {
  position: relative;
  top: -10px;
}

:global(.el-dialog__body) {
  padding: 0;
}

.el-col {
  line-height: 40px;
}
.el-input--small .el-input__inner {
  //height: 42px !important;
  //line-height: 32px;
}
.el-form-item {
  .el-input {
    width: 100px;
    background-color: aliceblue;
  }

  .el-select {
    width: 100px;
  }
}

.custom-color {
  color: red !important;
  /* 确保优先级高于其他样式 */
}

.el-table th {
  background-color: #f0f0f0;
  /* 修改表头背景色 */
  color: #333;
  /* 修改表头文字颜色 */
}

/* .demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
} */

.open-title {
  font-size: 20px;
  font-weight: 700;
  text-align: center;
}

/deep/.el-dialog__body {
  display: block !important;
}

.mt15 {
  margin-top: 15px;
}

.mb10 {
  margin-bottom: 10px;
}

.tc {
  text-align: center;
}

.align-center {
  align-items: center;
}

.space-between {
  justify-content: space-between;
}

.mt20 {
  margin-top: 20px;
}

.flex {
  display: flex;
  //height: 42px ;
}
</style>
